#!/usr/bin/env python
# encoding: utf-8
"""
    @author:水痕
    @time:2018-08-28 14:14:14:33
    @email:332904234@qq.com
    @version:1.0
    @fileName:login.py
    @describe:
"""
from django.http import HttpResponse
from geetest import GeetestLib
from django.views import View
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from users import models
from users.forms import LoginForm


class CustomBackend(ModelBackend):
    """
    定义校验用户登录(用户名、邮箱、手机号码登录)
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = models.UserProfileModel.objects.get(Q(username=username) | Q(email=username) | Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            print(e)
            return None


class LoginView(View):
    """
    用户登录视图类
    """

    def get(self, request, *args, **kwargs):
        next = request.GET.get('next', '')
        return render(request, 'login.html', locals())

    def post(self, request, *args, **kwargs):
        login_form = LoginForm(request.POST)
        next = request.GET.get('next', '')
        if login_form.is_valid():
            username = login_form.cleaned_data.get('username', None)
            password = login_form.cleaned_data.get('password', None)
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                # 手动设置session的时间
                # request.session.set_expiry(300)
                if next:
                    return redirect(next)
                return redirect('index')
        return self.get(request, {'message': login_form.errors})


class LogoutView(View):
    """
    用户退出视图
    """

    def get(self, request, *args, **kwargs):
        logout(request)
        return redirect('index')


pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"


def pcgetcaptcha(request):
    user_id = 'test'
    gt = GeetestLib(pc_geetest_id, pc_geetest_key)
    status = gt.pre_process(user_id)
    request.session[gt.GT_STATUS_SESSION_KEY] = status
    request.session["user_id"] = user_id
    response_str = gt.get_response_str()
    return HttpResponse(response_str)
